package com.oa.hyperion.api.v1;

import com.oa.hyperion.entity.assets.AssetsScrap;
import com.oa.hyperion.entity.assets.AssetsType;
import com.oa.hyperion.exception.AssetsTypeExistException;
import com.oa.hyperion.exception.SQLException;
import com.oa.hyperion.service.AssetsTypeService;
import com.oa.hyperion.utils.DBUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 资产类型controller
 * author yuanchongwei
 * date 2022-1-19
 */
@Api(value="资产类型controller",tags={"资产类型操作接口"})
@RestController
@RequestMapping("/v1/assets/type")
public class AssetsTypeController {
    @Autowired
    private AssetsTypeService assetsTypeService;

    @ApiOperation("获取所有资产类型")
    @GetMapping("all")
    public List<AssetsType> getAllTypes(){
        return assetsTypeService.getAssetsTypes();
    }

    // TODO 模糊查询
    @ApiOperation("资产id查询")
    @GetMapping("{id}")
    public AssetsType getAssetsType(@PathVariable int id){
        return assetsTypeService.getAssetsTypeById(id);
    }

    @ApiOperation("资产类型新增")
    @PostMapping("add")
    public String addAssetsType(@RequestBody AssetsType assetsType){
        //参数验证
        if (assetsType != null) {
            //添加之前判断数据库中是否已存在要添加的类型
            // 待添加的类型
            String typeToAdd = assetsType.getType();
            AssetsType astInDB = assetsTypeService.getAssetsTypeByType(typeToAdd);
            if (astInDB != null) {
                //资产类型已存在，抛出异常
                return "资产类型已存在，不可重复添加";
            }
            else{
                //数据库中不存在，则可以添加
                boolean result = assetsTypeService.insert(assetsType);
                if (result) {
                    //添加成功，返回添加的数据
                    return "添加成功";
                }
                else{
                    //添加失败，抛异常
                    throw new SQLException("数据库操作异常");
                }
            }
        }
        else{
            return "参数为空";
        }
    }
}
